import axios from 'axios';

const AK = 'sO9QWSRNkdVPWPSG9XKbX0qx';
const SK = 'q3Oww9mMnkdepdd8kMxV5pCGvcC9FIcp';

export enum OcrTypeEnum {
  标准精度 = 'https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token=',
  高精度 = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate?access_token=',
  网络图片 = 'https://aip.baidubce.com/rest/2.0/ocr/v1/webimage_loc?access_token=',
}

interface WordLocation {
  top: number;
  left: number;
  width: number;
  height: number;
}

interface WordsResult {
  words: string;
  location: WordLocation;
}

interface OcrResult {
  words_result: WordsResult[],
  words_result_num: number;
  log_id: number;
}

/**
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {

  let options = {
    'method': 'POST',
    'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
  };
  const url = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK;
  return axios.post(url).then(res => res.data.access_token);
}

/**
 * 获取文件base64编码
 * @param path
 */
function getFileContentAsBase64(path: string) {
  const fs = require('fs');
  try {
    return fs.promises.readFile(path, { encoding: 'base64' });
  } catch (err) {
    return Promise.reject(err);
  }
}


/**
 * 获取图片识别功能
 * api 详见百度云智能>人工智能Ai>文字识别
 * https://console.bce.baidu.com/ai/#/ai/ocr/overview/index
 */
export async function ocrImage(url, ocrType: OcrTypeEnum = OcrTypeEnum.标准精度) {
  const token = await getAccessToken();
  const base64Img = await getFileContentAsBase64(url);
  return axios({
    method: 'post',
    url: ocrType + token,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Accept': 'application/json'
    },
    data: {
      'image': base64Img,
      'detect_direction': 'false',
      'vertexes_location': 'false',
      'paragraph': 'false',
      'probability': 'false'
    }
  }).then((res) => {
    return res.data as OcrResult;
  });
}